<template>
  <div>
    <h3>用户列表组件</h3>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="queryData.query"
            clearable
            @clear="onClear"
            @keyup.enter="serchUser"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="serchUser"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
    </el-card>
    <!-- 根据获取到的用户数据列表,渲染表单 -->
    <el-table :data="userList" stripe style="width: 100%">
      <el-table-column type="index" label="#"> </el-table-column>
      <el-table-column prop="username" label="姓名"> </el-table-column>
      <el-table-column prop="email" label="邮箱"> </el-table-column>
      <el-table-column prop="mobile" label="电话"> </el-table-column>
      <el-table-column prop="role_name" label="角色"> </el-table-column>
      <el-table-column prop="mg_state" label="状态" width="80px">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            @change="changeState(scope.row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editUser(scope.row)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteUser(scope.row.id)"
          ></el-button>
          <el-tooltip
            class="item"
            effect="dark"
            content=" 权限分配"
            placement="top"
            :enterable="false"
          >
            <el-button
              type="warning"
              icon="el-icon-share"
              size="mini"
              @click="changeRole(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页导航区域 
      @size-change(pagesize改变时触发) 
      @current-change(页码发生改变时触发)
      :current-page(设置当前页码)
      :page-size(设置每页的数据条数)
      :total(设置总页数) -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryData.pagenum"
      :page-sizes="[1, 3, 5, 10]"
      :page-size="queryData.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 点击添加用户提示框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      @close="onClose"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addModel"
        :rules="addRules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addModel.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addModel.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addModel.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addModel.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击修改用户信息提示框 -->
    <el-dialog
      title="提示"
      :visible.sync="isEditShow"
      width="50%"
      @close="onClose"
    >
      <!-- 表单区域 -->
      <el-form
        :model="editModel"
        :rules="addRules"
        ref="editForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editModel.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editModel.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editModel.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditShow = false">取 消</el-button>
        <el-button type="primary" @click="doEidt">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击切换用户角色提示框 -->
    <el-dialog
      title="提示"
      :visible.sync="isChangeRole"
      width="50%"
      @close="onClose"
    >
      <!-- 表单区域 -->
      <el-form
        :model="rolesModel"
        ref="changeRoleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <p>用户名: {{ rolesModel.userName }}</p>
        <p>用户当前角色: {{ rolesModel.userRole }}</p>
        <p>
          选择新角色:
          <el-select v-model="choiceValue" placeholder="请选择">
            <el-option
              v-for="item in rolesValue"
              :key="item.id"
              :label="item.roleName"
              :value="item.roleName"
            >
            </el-option>
          </el-select>
        </p>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isChangeRole = false">取 消</el-button>
        <el-button type="primary" @click="doChange">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Service } from '../service/index'
export default {
  data() {
    return {
      userList: [],
      // 定义查询用户列表的数据
      queryData: {
        query: '', //关键字
        pagenum: 1, //页码
        pagesize: 3, //页容量
      },
      // 获取到的用户数量总数
      total: 0,
      // 添加用户对话框开关
      dialogVisible: false,
      // 编辑用户对话框开关
      isEditShow: false,
      // 切换用户角色对话框开关
      isChangeRole: false,
      // 定义添加用户数据
      addModel: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 定义编辑用户数据
      editModel: {
        username: '',
        email: '',
        mobile: '',
        id: -1,
      },
      // 定义切换用户角色
      rolesModel: {
        userName: '',
        userRole: '',
        userId: -1,
      },
      // 定义下拉选择框选中数据
      choiceValue: '',
      // 定义下拉选择框供选择的数据
      rolesValue: [],
      // 定义添加用户时数据验证
      addRules: {
        username: [
          { required: true, message: '请输入用户名~亲', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在3到15个字符~亲',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码哦~亲', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在3到15个字符~亲',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱哦~亲', trigger: 'blur' },
          {
            type: 'email',
            message: '邮箱格式好像不争取哦~亲',
            trigger: 'blur',
          },
        ],
        mobile: [
          {
            required: true,
            pattern: /^(13|14|15|16|17|18|19)[0-9]\d{8}$/,
            message: '请输入正确的手机号哦~亲',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  // 数据平铺时请求数据
  async created() {
    this.getUserList()
    this.getRolesList()
  },
  methods: {
    // 根据页容量渲染列表
    handleSizeChange(newSize) {
      //pagesize改变时触发，当pagesize发生改变的时候，我们应该
      //以最新的pagesize来请求数据并展示数据
      this.queryData.pagesize = newSize
      //重新按照pagesize发送请求，请求最新的数据
      this.getUserList()
    },
    // 页码改变,重新渲染列表
    handleCurrentChange(current) {
      //页码发生改变时触发当current发生改变的时候，我们应该
      //以最新的current页码来请求数据并展示数据
      this.queryData.pagenum = current
      //重新按照pagenum发送请求，请求最新的数据
      this.getUserList()
    },
    // 获取用户列表
    async getUserList() {
      const res = await Service.getUsers(this.queryData)
      if (res.data.meta.status !== 200) {
        return this.$message.error(res.data.meta.msg)
      } else {
        this.userList = res.data.data.users
        this.total = res.data.data.total
      }
    },
    // 状态切换
    async changeState(data) {
      const res = await Service.setState(data.id, data.mg_state)
      if (res.data.meta.status !== 200) {
        data.mg_state = !data.mg_state
        return this.$message.error(res.data.meta.msg)
      } else {
        return this.$message.success(res.data.meta.msg)
      }
    },
    // 搜索用户
    serchUser() {
      this.getUserList()
    },
    // 重新获取用户列表
    onClear() {
      this.getUserList()
    },
    // 关闭弹窗
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          done()
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 清除表单数据
    onClose() {
      this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
      this.$refs.changeRoleForm && this.$refs.changeRoleForm.resetFields()
      this.$refs.editForm && this.$refs.editForm.resetFields()
    },

    // 添加用户数据
    addUsers() {
      // 点击时校验数据
      this.$refs.ruleForm.validate(async (isOk) => {
        // 成功
        if (isOk) {
          const res = await Service.addUsers(this.addModel)
          if (res.data.meta.status !== 200) {
            this.$message.error(res.data.meta.msg)
          } else {
            this.$message.success(res.data.meta.msg)
            if (this.userList.length === this.queryData.pagesize) {
              this.queryData.pagenum++
            }
            this.getUserList()
            this.dialogVisible = false
          }
        } else {
          this.$message.error('对不起信息未通过校验')
        }
      })
    },
    // 展示编辑用户的对话框
    editUser(data) {
      this.isEditShow = true
      this.editModel.username = data.username
      this.editModel.email = data.email
      this.editModel.mobile = data.mobile
      this.editModel.id = data.id
    },
    // 确认修改操作
    doEidt() {
      // 点击时校验数据
      this.$refs.editForm.validate(async (isOk) => {
        // 成功
        if (isOk) {
          const res = await Service.editUserInfo(this.editModel)
          if (res.data.meta.status !== 200) {
            this.$message.error(res.data.meta.msg)
          } else {
            this.$message.success(res.data.meta.msg)
            this.userList.forEach((item) => {
              if (item.id == res.data.data.id) {
                item.mobile = res.data.data.mobile
                item.email = res.data.data.email
              }
            })
            this.isEditShow = false
          }
        } else {
          this.$message.error('对不起信息未通过校验')
        }
      })
    },
    // 删除用户操作
    async deleteUser(id) {
      try {
        await this.$msgBox.confirm('删除数据后不可恢复,您还要继续么', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        const res = await Service.deleteUser(id)
        this.$message.success(res.data.meta.msg)
        if (this.userList.length === 1) {
          this.queryData.pagenum--
        }
        this.getUserList()
      } catch (error) {
        console.log(error)
      }
    },
    // 切换用户角色
    async changeRole(data) {
      this.isChangeRole = true
      this.rolesModel.userName = data.username
      this.rolesModel.userRole = data.role_name
      this.rolesModel.userId = data.id
    },
    // 确认修改
    async doChange() {
      this.isChangeRole = false
      let roleId = -1
      const id = this.rolesModel.userId
      this.rolesValue.forEach((item) => {
        if (item.roleName === this.choiceValue) {
          roleId = item.id
        }
      })
      const res = await Service.changRole(id, roleId)
      if (res.data.meta.status !== 200) {
        this.$message.error(res.data.meta.msg)
      } else {
        this.$message.success(res.data.meta.msg)
        this.getUserList()
      }
    },
    // 获取角色列表数据
    async getRolesList() {
      const res = await Service.getRoles()
      this.rolesValue = res.data.data
    },
  },
}
</script>

<style scoped>
</style>